package com.lincoln.Client.frames;

import com.lincoln.Client.context.FrameContext;
import com.lincoln.Client.context.RobotContext;
import com.lincoln.wechat.WeChatBot;
import com.lincoln.wechat.utils.StringUtils;
import lombok.Getter;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

@Getter
public class LoginFrame extends BaseFrame {
    private JFrame jFrame;
    private JPanel panel1;
    private JLabel bottom;
    private JLabel header;
    private JLabel image;
    private String key;//此次登陆的机器人key
    private Thread thread;//监听登陆的线程

    public LoginFrame() {
        jFrame = new JFrame();
        panel1 = new JPanel();
        panel1.setLayout(new BorderLayout());
        header = new JLabel("添加微信账号");
        panel1.add("North", header);
        image = new JLabel("正在加载二维码...");
        panel1.add("Center", image);
        bottom = new JLabel("请使用手机微信扫描二维码添加微信账号");
        panel1.add("South", bottom);

        key = RobotContext.addBot();
        thread = new Thread(RobotContext.getRobot(key), key);
        thread.start();
        jFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                if (RobotContext.getRobot(key) != null && !RobotContext.getRobot(key).isRunning()) {
                    RobotContext.removeRobot(key);
                }
                jFrame.dispose();
            }

        });
        while (RobotContext.getRobot(key).api() == null || RobotContext.getRobot(key).api().qrCode() == null) {
        }
        try {
            File qrCode = RobotContext.getRobot(key).api().qrCode();
            InputStream input = new FileInputStream(qrCode);
            byte[] byt = new byte[input.available()];
            input.read(byt);
            image(byt);
            image.setText("");
        } catch (Exception e) {
            image.setText("加载失败!");
        }
        Runnable waitLogin = new Runnable() {
            @Override
            public void run() {
                //等待登陆成功
                while (StringUtils.isEmpty(RobotContext.getRobot(key).getSession().getUserName()) || RobotContext.getRobot(key).api().logging()) {
                }
                jFrame.dispose();
                FrameContext.login = null;
                FrameContext.accountManage.flashFrame();
            }
        };
        new Thread(waitLogin).start();
    }

    /**
     * 窗口构建
     *
     * @return
     */
    public JFrame getFrame() {
        jFrame.setContentPane(this.panel1);
//        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.pack();
        return jFrame;
    }

    public void image(byte[] bytes) {
        image.setIcon(new ImageIcon(bytes));
    }
}
